//
//  ZLCameraVC.m
//  ZLCamera
//
//  Created by 科大 on 2024/4/18.
//

#import "ZLCameraVC.h"
#import <AVFoundation/AVFoundation.h>
#import "ZLCaptureTool.h"
#import "ZLFocusView.h"
#import "ZLMakeView.h"
#import <Masonry/Masonry.h>
#import <Photos/Photos.h>
@interface ZLCameraVC ()<ZLCaptureToolDelegate>
/// 摄像头采集工具
@property (nonatomic, strong) ZLCaptureTool *avCaptureTool;
/// 捕获预览视图
@property (nonatomic, strong) UIImageView *captureView;
/// 切换前后摄像头
@property (nonatomic, strong) UIButton *switchCameraBtn;
/// 返回
@property (nonatomic, strong) UIButton *closeButton;
/// 拍摄提示语  轻触拍照 长按拍摄
@property (nonatomic, strong) UILabel *tipsLabel;
/// 当前焦距比例系数
@property (nonatomic, assign) CGFloat currentZoomFactor;
/// 当前聚焦视图
@property (nonatomic, strong) ZLFocusView *focusView;
/// 拍摄
@property (nonatomic, strong) ZLMakeView *makeView;
@end

@implementation ZLCameraVC

- (instancetype)init {
    if (self = [super init]) {
        self.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return self;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_avCaptureTool stopRunning];
    [self.makeView cancelTimer];
    [_avCaptureTool removeObserver:self forKeyPath:@"shootingOrientation"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.avCaptureTool startRunning];
    //监听设备方向，旋转切换摄像头按钮
    [self.avCaptureTool addObserver:self forKeyPath:@"shootingOrientation" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.focusView];
    [self.view addSubview:self.makeView];
    [self.view addSubview:self.closeButton];
    [self.view addSubview:self.switchCameraBtn];
    [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.makeView);
        make.right.equalTo(self.makeView.mas_left).offset(-50);
        make.width.height.mas_equalTo(40);
    }];
    [self.switchCameraBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.makeView);
        make.left.equalTo(self.makeView.mas_right).offset(50);
        make.width.height.mas_equalTo(40);
    }];
}

#pragma mark - action
- (void)closeButton:(UIButton *)btn {
    [self dismissViewControllerAnimated:YES completion:nil];
}
//切换前/后摄像头
- (void)switchCameraClicked:(id)sender {
    if (self.avCaptureTool.devicePosition == AVCaptureDevicePositionFront) {
        [self.avCaptureTool switchsCamera:AVCaptureDevicePositionBack];
    } else if(self.avCaptureTool.devicePosition == AVCaptureDevicePositionBack) {
        [self.avCaptureTool switchsCamera:AVCaptureDevicePositionFront];
    }
}

#pragma mark - SLAvCaptureToolDelegate  图片、音视频输出代理
//图片输出完成
- (void)captureTool:(ZLCaptureTool *)captureTool didOutputPhoto:(UIImage *)image error:(NSError *)error {
    if (self.photoComplete) {
        self.photoComplete(image, error);
    }
}
//音视频输出完成
- (void)captureTool:(ZLCaptureTool *)captureTool didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL error:(NSError *)error {
    if (self.videoComplete) {
        self.videoComplete(outputFileURL, error);
    }
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"shootingOrientation"]) {
        UIDeviceOrientation deviceOrientation = [change[@"new"] intValue];
        [UIView animateWithDuration:0.3 animations:^{
            switch (deviceOrientation) {
                case UIDeviceOrientationPortrait:
                    self.switchCameraBtn.transform = CGAffineTransformMakeRotation(0);
                    break;
                case UIDeviceOrientationLandscapeLeft:
                    self.switchCameraBtn.transform = CGAffineTransformMakeRotation(M_PI/2.0);
                    break;
                case UIDeviceOrientationLandscapeRight:
                    self.switchCameraBtn.transform = CGAffineTransformMakeRotation(-M_PI/2.0);
                    break;
                case UIDeviceOrientationPortraitUpsideDown:
                    self.switchCameraBtn.transform = CGAffineTransformMakeRotation(-M_PI);
                    break;
                default:
                    break;
            }
        }];
    }
}

#pragma mark - init

- (ZLCaptureTool *)avCaptureTool {
    if (_avCaptureTool == nil) {
        _avCaptureTool = [[ZLCaptureTool alloc] init];
        _avCaptureTool.preview = self.view;
        _avCaptureTool.delegate = self;
        _avCaptureTool.videoSize = CGSizeMake(self.view.frame.size.width*0.8, self.view.frame.size.height*0.8);
    }
    return _avCaptureTool;
}
- (UIButton *)closeButton {
    if (_closeButton == nil) {
        _closeButton = [[UIButton alloc] init];
        _closeButton.frame = CGRectMake(0, 0, 30, 30);
        _closeButton.center = CGPointMake((self.view.frame.size.width/2 - 70/2.0)/2.0, self.view.frame.size.height - 80);
        [_closeButton setImage:[self image:@"close"] forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(closeButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeButton;
}
- (UIButton *)switchCameraBtn {
    if (_switchCameraBtn == nil) {
        _switchCameraBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 30 - 30, 44 , 30, 30)];
        [_switchCameraBtn setImage:[self image:@"change"] forState:UIControlStateNormal];
        [_switchCameraBtn setContentMode:UIViewContentModeScaleAspectFit];
        [_switchCameraBtn addTarget:self action:@selector(switchCameraClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _switchCameraBtn;
}
- (UILabel *)tipsLabel {
    if (_tipsLabel == nil) {
        _tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 140)/2.0, self.makeView.frame.origin.y - 20 - 30, 140, 20)];
        _tipsLabel.textColor = [UIColor whiteColor];
        _tipsLabel.font = [UIFont systemFontOfSize:14];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.text = @"轻触拍照，按住摄像";
    }
    return  _tipsLabel;
}

- (ZLFocusView *)focusView {
    if (!_focusView) {
        __weak typeof(self) weakSelf = self;
        _focusView = [[ZLFocusView alloc] initWithFrame:self.view.bounds];
        _focusView.focusTap = ^(CGPoint point) {
            [weakSelf.avCaptureTool focusAtPoint:point];
        };
        [_focusView pinch:^{
            self.currentZoomFactor = self.avCaptureTool.videoZoomFactor;
        } change:^(CGFloat value) {
            self.avCaptureTool.videoZoomFactor = self.currentZoomFactor * value;
        }];
    }
    return _focusView;
}

- (ZLMakeView *)makeView {
    if (!_makeView) {
        __weak typeof(self) weakSelf = self;
        _makeView = [[ZLMakeView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 80) / 2.0, self.view.frame.size.height - 130, 80, 80)];
        _makeView.makePhoto = ^{
            [weakSelf.avCaptureTool outputPhoto];
        };
        _makeView.makeVideo = ^(CGFloat progress, ZLMakeVideoStatus status) {
            if (status == ZLMakeVideoStatusStart) {
                [weakSelf.avCaptureTool startRecordVideoToOutputFileAtPath:[weakSelf getVideoPath] recordType:ZLCaptureTypeAv];
            } else if (status == ZLMakeVideoStatusEnd) {
                [weakSelf.avCaptureTool stopRecordVideo];
            }
        };
    }
    return _makeView;
}

- (NSString *)getVideoPath {
    NSString *path = [NSTemporaryDirectory() stringByAppendingString:@"zlca.mp4"];
    return path;
}

- (UIImage *)image:(NSString *)named {
    if (named == nil || named.length == 0) {
        return nil;
    }
    NSBundle *frameworkBundle = [NSBundle bundleForClass:[self class]];
    NSBundle *imageBundle = [NSBundle bundleWithPath:[frameworkBundle pathForResource:@"ZLCamera" ofType:@"bundle"]];
    UIImage *image = [UIImage imageNamed:named inBundle:imageBundle compatibleWithTraitCollection:nil];
    if (image == nil) {
        return [[UIImage alloc] init];
    }
    return image;
}

@end
